﻿using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Spreadsheet;
using DocumentFormat.OpenXml.Wordprocessing;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Run = DocumentFormat.OpenXml.Wordprocessing.Run;
using Table = DocumentFormat.OpenXml.Wordprocessing.Table;
using Text = DocumentFormat.OpenXml.Wordprocessing.Text;

namespace OpenXmlTools.OpenXML.Word
{
    /// <summary>
    /// Word表格合并单元格帮助类
    /// </summary>
    public static class WordTableMergeHelper
    {
        /// <summary>
        /// 合并表格单元格
        /// </summary>
        /// <param name="table">表格对象</param>
        /// <param name="startRow">起始行索引（从0开始）</param>
        /// <param name="startColumn">起始列索引（从0开始）</param>
        /// <param name="endRow">结束行索引（从0开始）</param>
        /// <param name="endColumn">结束列索引（从0开始）</param>
        public static void MergeCells(Table table, int startRow, int startColumn, int endRow, int endColumn)
        {
            if (table == null) throw new ArgumentNullException(nameof(table));
            if (startRow < 0 || startColumn < 0 || endRow < 0 || endColumn < 0)
                throw new ArgumentException("行列索引不能为负数");
            if (startRow > endRow || startColumn > endColumn)
                throw new ArgumentException("起始位置不能大于结束位置");

            // 获取表格行
            var rows = table.Elements<TableRow>().ToList();
            if (endRow >= rows.Count)
                throw new ArgumentOutOfRangeException(nameof(endRow), "结束行索引超出表格范围");

            // 检查列索引是否有效
            if (rows[startRow].Elements<TableCell>().Count() <= endColumn ||
                rows[endRow].Elements<TableCell>().Count() <= endColumn)
                throw new ArgumentOutOfRangeException(nameof(endColumn), "结束列索引超出表格范围");

            // 创建合并单元格对象
            var mergeCell = new MergeCell
            {
                Reference = new StringValue($"{GetCellReference(startRow, startColumn)}:{GetCellReference(endRow, endColumn)}")
            };

            // 获取或创建表格属性
            var tableProperties = table.GetFirstChild<TableProperties>();
            if (tableProperties == null)
            {
                tableProperties = new TableProperties();
                table.PrependChild(tableProperties);
            }

            // 获取或创建合并单元格列表
            var mergeCells = tableProperties.GetFirstChild<MergeCells>();
            if (mergeCells == null)
            {
                mergeCells = new MergeCells();
                tableProperties.Append(mergeCells);
            }

            // 添加合并单元格定义
            mergeCells.Append(mergeCell);

            // 实际合并单元格
            for (int row = startRow; row <= endRow; row++)
            {
                var cells = rows[row].Elements<TableCell>().ToList();
                for (int col = startColumn; col <= endColumn; col++)
                {
                    if (row == startRow && col == startColumn)
                    {
                        // 起始单元格 - 设置跨行跨列属性
                        SetCellSpanProperties(cells[col], endRow - startRow + 1, endColumn - startColumn + 1);
                    }
                    else
                    {
                        // 被合并的单元格 - 标记为已合并
                        SetCellAsMerged(cells[col]);
                    }
                }
            }
        }

        /// <summary>
        /// 获取单元格引用字符串（如"A1"）
        /// </summary>
        /// <param name="row">单元格行索引</param>
        /// <param name="column">单元格列索引</param>
        /// <returns>单元格引用字符串</returns>
        private static string GetCellReference(int row, int column)
        {
            string columnName = "";
            int col = column + 1;
            while (col > 0)
            {
                int modulo = (col - 1) % 26;
                columnName = Convert.ToChar('A' + modulo) + columnName;
                col = (col - modulo) / 26;
            }
            return $"{columnName}{row + 1}";
        }

        /// <summary>
        /// 设置单元格跨行跨列属性
        /// </summary>
        /// <param name="cell">单元格</param>
        /// <param name="rowSpan">单元格跨行数</param>
        /// <param name="colSpan">单元格跨列数</param>
        private static void SetCellSpanProperties(TableCell cell, int rowSpan, int colSpan)
        {
            // 获取或创建单元格属性
            var cellProperties = cell.GetFirstChild<TableCellProperties>();
            if (cellProperties == null)
            {
                cellProperties = new TableCellProperties();
                cell.PrependChild(cellProperties);
            }

            // 设置垂直合并（跨行）
            if (rowSpan > 1)
            {
                var vMerge = cellProperties.GetFirstChild<VerticalMerge>();
                if (vMerge == null)
                {
                    vMerge = new VerticalMerge { Val = new EnumValue<MergedCellValues>(MergedCellValues.Restart) };
                    cellProperties.Append(vMerge);
                }
                else
                {
                    vMerge.Val = new EnumValue<MergedCellValues>(MergedCellValues.Restart);
                }
            }

            // 设置水平合并（跨列）
            if (colSpan > 1)
            {
                var gridSpan = cellProperties.GetFirstChild<GridSpan>();
                if (gridSpan == null)
                {
                    gridSpan = new GridSpan { Val = colSpan };
                    cellProperties.Append(gridSpan);
                }
                else
                {
                    gridSpan.Val = colSpan;
                }
            }
        }

        /// <summary>
        /// 标记单元格为已合并
        /// </summary>
        /// <param name="cell">单元格</param>
        private static void SetCellAsMerged(TableCell cell)
        {
            // 获取或创建单元格属性
            var cellProperties = cell.GetFirstChild<TableCellProperties>();
            if (cellProperties == null)
            {
                cellProperties = new TableCellProperties();
                cell.PrependChild(cellProperties);
            }

            // 设置垂直合并为继续
            var vMerge = cellProperties.GetFirstChild<VerticalMerge>();
            if (vMerge == null)
            {
                vMerge = new VerticalMerge { Val = new EnumValue<MergedCellValues>(MergedCellValues.Continue) };
                cellProperties.Append(vMerge);
            }
            else
            {
                vMerge.Val = new EnumValue<MergedCellValues>(MergedCellValues.Continue);
            }

            // 移除内容（可选，根据需要决定是否保留）
            // cell.RemoveAllChildren<Paragraph>();
        }

        /// <summary>
        /// 合并单元格并设置内容
        /// </summary>
        /// <param name="table">表格对象</param>
        /// <param name="startRow">起始行索引（从0开始）</param>
        /// <param name="startColumn">起始列索引（从0开始）</param>
        /// <param name="endRow">结束行索引（从0开始）</param>
        /// <param name="endColumn">结束列索引（从0开始）</param>
        /// <param name="content">单元格内容</param>
        public static void MergeCellsWithContent(Table table, int startRow, int startColumn, int endRow, int endColumn, string content)
        {
            // 先合并单元格
            MergeCells(table, startRow, startColumn, endRow, endColumn);

            // 获取起始单元格
            var startCell = table.Elements<TableRow>().ElementAt(startRow)
                             .Elements<TableCell>().ElementAt(startColumn);

            // 清除原有内容
            startCell.RemoveAllChildren<Paragraph>();

            // 添加新内容
            var paragraph = new Paragraph();
            var run = new Run();
            var text = new Text(content);
            run.Append(text);
            paragraph.Append(run);
            startCell.Append(paragraph);
        }

        /// <summary>
        /// 合并整行单元格
        /// </summary>
        /// <param name="table">表格对象</param>
        /// <param name="rowIndex">行索引</param>
        /// <param name="startColumn">起始列索引</param>
        /// <param name="endColumn">结束列索引</param>
        public static void MergeRowCells(Table table, int rowIndex, int startColumn, int endColumn)
        {
            MergeCells(table, rowIndex, startColumn, rowIndex, endColumn);
        }

        /// <summary>
        /// 合并整列单元格
        /// </summary>
        /// <param name="table">表格对象</param>
        /// <param name="columnIndex">列索引</param>
        /// <param name="startRow">起始行索引</param>
        /// <param name="endRow">结束行索引</param>
        public static void MergeColumnCells(Table table, int columnIndex, int startRow, int endRow)
        {
            MergeCells(table, startRow, columnIndex, endRow, columnIndex);
        }

        /// <summary>
        /// 批量合并单元格
        /// </summary>
        /// <param name="table">表格对象</param>
        /// <param name="mergeRegions">合并单元格区域</param>
        public static void BatchMergeCells(Table table, List<(int startRow, int startCol, int endRow, int endCol)> mergeRegions)
        {
            foreach (var region in mergeRegions)
            {
                MergeCells(table, region.startRow, region.startCol, region.endRow, region.endCol);
            }
        }
    }
}
